You're working with an intern that keeps coming to you with JavaScript code that won't run because the braces, brackets, and parentheses are off. To save you both some time, you decide to write a braces/brackets/parentheses validator.
Let's say:
Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
Examples:
We iterate through our string, making sure that:
We use a stack to keep track of the most recently seen, unclosed opener. And if the stack is ever empty when we come to a closer, we know that closer doesn't have an opener.
So as we iterate:
If we finish iterating and our stack is empty, we know every opener was properly closed.
def is_valid(code):
openers_to_closers = {
'(' : ')',
'{' : '}',
'[' : ']',
}
openers = set(openers_to_closers.keys())
closers = set(openers_to_closers.values())
openers_stack = []
for char in code:
if char in openers:
openers_stack.append(char)
elif char in closers:
if not openers_stack:
return False
else:
last_unclosed_opener = openers_stack.pop()
# If this closer doesn't correspond to the most recently
# seen unclosed opener, short-circuit, returning False
if not openers_to_closers[last_unclosed_opener] == char:
return False
return openers_stack == []
time (one iteration through the string), and space (in the worst case, all of our characters are openers, so we push them all onto the stack).
In Ruby, sometimes expressions are surrounded by vertical bars, "|like this|". Extend your validator to validate vertical bars. Careful: there's no difference between the "opener" and "closer" in this case—they're the same character!
The trick was to use a stack.
It might have been difficult to have that insight, because you might not use stacks that much.
Two common uses for stacks are:
So remember, if you're doing either of those things, try using a stack!
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io